package ui;

import java.awt.TextField;

/**
 * This class combines model and view for a numeric edit field.
 * 
 * @version 1.0
 * @author Hans U. Gerber (<a
 *         href="mailto:gerber@ifh.ee.ethz.ch">gerber@ifh.ee.ethz.ch</a>)
 */
public class NumberUI extends TextField implements Validatable {
	private String label;
	private double value;
	private double min;
	private double max;

	/**
	 * @param label
	 *            a descriptive text label for the edit field
	 * @param initValue
	 *            the initial value of the number
	 * @param max
	 *            the maximum value allowed
	 * @param min
	 *            the minimum value allowed
	 */
	public NumberUI(String label, double initValue, double min, double max) {
		super();
		this.label = label;
		this.min = min;
		this.max = max;
		this.value = initValue;
		display();
	}

	public String getLabel() {
		return label;
	}

	public void display() {
		setText("" + value);
	}

	/**
	 * @return the numeric value that was last accepted
	 */
	public double doubleValue() {
		return value;
	}

	/**
	 * @return the numeric value that was last accepted, converted to an integer
	 */
	public int intValue() {
		return (int) value;
	}

	/**
	 * Checks the contents of the edit field to see if they form a valid number
	 * within the specified range.
	 * 
	 * @return <code>null</code> if the contents of the edit field are valid, an
	 *         error message otherwise
	 */
	public String check() {
		double x;
		boolean ok;
		try {
			x = java.lang.Double.valueOf(getText().trim()).doubleValue();
			ok = true;
		} catch (NumberFormatException e) {
			x = 0;
			ok = false;
		}
		ok = ok && (x >= min && x <= max);
		if (ok) {
			return null;
		} else {
			return "\"" + label + "\" must be in the range " + min + " to "
					+ max + ".";
		}
	}

	/**
	 * Converts the contents of the edit field into a number and stores it in
	 * the data model of this component. This method assumes that the edit field
	 * has already been validated by method <code>check</code>.
	 */
	public void accept() {
		double x;
		try {
			x = java.lang.Double.valueOf(getText().trim()).doubleValue();
		} catch (NumberFormatException e) {
			x = 0;
		}
		value = x;
	}

	public double getMin() {
		return min;
	}

	public double getMax() {
		return max;
	}
}
